<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>群组管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            margin: 8px;
            font-family: 'Arial', sans-serif;
            text-align: center;
        }

        .showStudentDiv {
            background-size: cover;
            width: 700px;
            height: 200px;
            margin: auto;
            margin-top: 50px;

        }

        .item a {
            background-color: lightgrey;
            text-decoration: none;
            font-size: 15px;
            color: black;
            border-radius: 3px;
        }


        table {
            width: 100%;
            border-collapse: collapse;
            background-color: rgba(255, 255, 255, 0.9);
            opacity: 0.8;
        }

        table body {
            display: block;
            height: 300px;
            overflow-y: scroll;
        }

        table td {
            border: 1px solid #A6A6A6;
            height: 30px;
            width: 300px;
            text-align: center;
            font-size: 15px;
        }

        button {
            background-color: cornflowerblue;
            border: 1px solid #dcdfe6;
            color: #303133;
            padding: 6px 12px;
            text-align: center;
            border-radius: 4px;
            cursor: pointer;
        }

        button.disabled {
            background-color: gray;
            border: 1px solid #dcdfe6;
            color: #303133;
            padding: 6px 12px;
            text-align: center;
            border-radius: 4px;
            cursor: pointer;
        }

        nav {
            background-color: #f2f2f2;
            padding: 10px 0;
            text-align: center;
        }

        nav a {
            padding: 14px 20px;
            text-decoration: none;
            color: black;
            display: inline-block;
            cursor: pointer; /* 添加鼠标指针样式，让链接看起来可点击 */
        }

        nav a:hover {
            background-color: #ddd;
        }

        .dropdown {
            position: relative;
            display: inline-block;
        }

        .dropbtn {
            padding: 14px 20px;
            text-decoration: none;
            color: black;
            cursor: pointer; /* 添加鼠标指针样式，让链接看起来可点击 */
        }

        .dropdown-content {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 160px;
            box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
            z-index: 1;
        }

        .dropdown:hover .dropdown-content {
            display: block;
        }

        .dropdown-content a {
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
            cursor: pointer; /* 添加鼠标指针样式，让链接看起来可点击 */
        }

        .dropdown-content a:hover {
            background-color: #f1f1f1;
        }
    </style>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>

        function getCookie(cookieName) {
            const strCookie = document.cookie
            const cookieList = strCookie.split(';')

            for (let i = 0; i < cookieList.length; i++) {
                const arr = cookieList[i].split('=')
                if (cookieName === arr[0].trim()) {
                    return arr[1]
                }
            }

            return ''
        }


        document.addEventListener('DOMContentLoaded', function () {
            // 群组点击事件
            document.getElementById('groupLink').addEventListener('click', function (event) {
                if (!checkUserLoggedIn()) {
                    alert('您尚未登录，请先登录');
                    window.location.href = '/page/toLoginPage'; // 模拟跳转到登录页面
                    event.preventDefault();
                }
            });

            // 个人资料点击事件
            document.getElementById('profileLink').addEventListener('click', function (event) {
                if (!checkUserLoggedIn()) {
                    alert('您尚未登录，请先登录');
                    window.location.href = '/page/toLoginPage'; // 模拟跳转到登录页面
                    event.preventDefault();
                }
            });

            // 校验用户是否已登录的函数
            function checkUserLoggedIn() {
                // 这里可以编写校验cookie中用户是否登录的逻辑，返回 true 或 false
                // 假设这里使用一个名为 isUserLoggedIn 的函数来校验
                return isUserLoggedIn();
            }

            // 这里是模拟的校验用户是否已登录的函数
            function isUserLoggedIn() {
                // 假设在 cookie 中有一个名为 'loggedIn' 的标识，表示用户是否已登录
                const username = getCookie('username')
                // alert(username)
                // 返回 true 表示已登录，返回 false 表示未登录
                return username !== '';

            }
        });

        $.ajax({
            url: "/groups/getGroup",
            type: "get",
            data: {
                username: "${username}"
            },
            success: function (response) {
                console.log(response)
                if (response != "") {
                    for (var i = 0; i < response.length; i++) {
                        var mygroup = response[i];
                        var row = $("<tr></tr>");
                        row.append($("<td>").text(mygroup.groupid));
                        row.append($("<td>").text(mygroup.groupname));
                        row.append($("<td>").text(mygroup.creator));
                        var username = "${username}";
                        if (mygroup.creator == username) row.append($("<td>").append($("<button>").attr("id", "exitbutton").attr("onclick", "deletegroups('" + mygroup.groupname + "','" + "${username}" + "')").text("解散")));
                        else row.append($("<td>").append($("<button>").attr("id", "exitbutton").attr("onclick", "exitgroups('" + mygroup.groupname + "','" + "${username}" + "')").text("退出")));
                        row.append($("<td>").append( '<a href="/page/toGroupDetail?groupId='+mygroup.groupid+'" target="_blank"><button>查看小组</button></a>'))
                        $("#mygrouplist").append(row);
                    }
                } else {
                    const row = $("#grouplist");
                    row.empty();
                }
            },
            error: function (xhr, status, error) {
            }
        });
        <%--console.log(${mygroups});--%>

        function reload() {
            window.location.href = "/page/toGroupPage";
        }

        function searchgroups() {
            var searchText = $("#search-input").val();
            if (searchText.length === 0) reload();
            console.log(searchText);
            $.ajax({
                url: "/groups/searchGroup/" + searchText,
                type: "get",
                success: function (response) {
                    console.log(response)
                    if (response != "") {
                        $("#list tr:gt(1)").remove();
                        for (var i = 0; i < response.length; i++) {
                            var searchgroups = response[i];
                            var row = $("<tr></tr>").attr("id", "searchlist");
                            row.append($("<td>").text(searchgroups.groupid));
                            row.append($("<td>").text(searchgroups.groupname));
                            row.append($("<td>").text(searchgroups.creator));
                            row.append($("<td>").append($("<button>").attr("id", "joinbutton").attr("onclick", "joingroups('" + searchgroups.groupname + "','" + "${username}" + "')").text("加入")));
                            $("#list").append(row);
                        }
                    } else {
                        $("#list tr:gt(1)").remove();
                    }
                },
                error: function (xhr, status, error) {
                }
            });
        };

        function creategroups() {
            $("#createGroupModal").modal("show");
        };

        function submitgroups() {
            var groupname = $("#groupName").val();
            var params = {
                groupname: groupname,
                username: "${username}"
            }
            if (groupName) {
                $.ajax({
                    url: "/groups/createGroup",
                    type: "get",
                    data: params,
                    success: function (response) {
                        if (response == true) {
                            alert("群组创建成功");
                            $("#createGroupModal").modal("hide");
                            reload();
                        } else {
                            alert("群组创建失败");
                        }
                    },
                    error: function (xhr, status, error) {
                        alert("群组创建失败");
                    }
                });
            } else {
                alert("请输入群组名");
            }
        };

        function joingroups(groupname, username) {
            var params = {
                username: username,
                groupname: groupname
            }
            $.ajax({
                url: "/groups/joinGroup",
                type: "get",
                data: params,
                success: function (response) {
                    if (response) {
                        alert("加入成功");
                        $("#joinbutton").addClass("disabled").prop("disabled", true);
                        reload();
                    } else {
                        alert("不可加入");
                        $("#joinbutton").addClass("disabled").prop("disabled", true);
                        reload();
                    }
                },
                error: function (xhr, status, error) {
                }
            });
        };

        function exitgroups(groupname, username) {
            var params = {
                username: username,
                groupname: groupname
            }
            $.ajax({
                url: "/groups/exitGroup",
                type: "get",
                data: params,
                success: function (response) {
                    alert("退出成功");
                    reload();
                },
                error: function (xhr, status, error) {
                    alert("退出失败");
                }
            });
        };

        function deletegroups(groupname, username) {
            var params = {
                username: username,
                groupname: groupname
            }
            $.ajax({
                url: "/groups/deleteGroup",
                type: "get",
                data: params,
                success: function (response) {
                    alert("解散成功");
                    reload();
                },
                error: function (xhr, status, error) {
                    alert("解散失败");
                }
            });
        };
    </script>
</head>
<body>
<nav>
    <a href="/">首页</a>
    <div class="dropdown">
        <a class="dropbtn">群组</a>
        <div class="dropdown-content">
            <a href="/page/toGroupPage" id="groupLink">群组管理</a>
            <a href="/page/toChatRoomPage" id="chatLink">群组聊天</a>
        </div>
    </div>
    <a href="/page/toAnswerPage">智能问答</a>
    <div class="dropdown">
        <a class="dropbtn">个人中心</a>
        <div class="dropdown-content">
            <a href="/page/toUserCenterPage" id="profileLink">个人资料</a>
            <a href="/page/toNotificationPage" id="notificationLink">通知</a>
            <a href="/page/Exit">登出</a>
        </div>
    </div>
</nav>
<div class="container">
    <div id="createGroupModal" class="modal fade" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">创建群组</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <label for="groupName">群组名：</label>
                    <input type="text" id="groupName" class="form-control">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" onclick="submitgroups()" id="confirmCreateGroup" class="btn btn-primary">
                        确认创建
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="showStudentDiv">
    <h3>查找群组</h3>
    <table border="2" cellspacing="0" id="list">
        <tr class="title-row">
            <td colspan="8">
                按名称查询：<input type="text" id="search-input" value=""/>
                <button onclick="searchgroups()">查询</button>
                <button onclick="creategroups()">创建群组</button>
            </td>
        </tr>
        <tr align="center" class="title-row">
            <td>编号</td>
            <td>组群名称</td>
            <td>创建者</td>
            <td>操作</td>
        </tr>
    </table>
</div>
<div class="showStudentDiv">
    <h3>我的群组</h3>
    <table border="2" cellspacing="0" id="mygrouplist">
        <tr align="center">
            <td>编号</td>
            <td>组群名称</td>
            <td>创建者</td>
            <td colspan="2">操作</td>
        </tr>
    </table>
</div>
</body>
</html>